package com.ctrip.openapi.java.customed;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;
import org.xml.sax.InputSource;

import com.ctrip.openapi.java.base.DBPool;
import com.ctrip.openapi.java.base.HttpAccessAdapter;
import com.ctrip.openapi.java.base.model.City;
import com.ctrip.openapi.java.base.model.Hotel;
import com.ctrip.openapi.java.base.model.RelativePosition;
import com.ctrip.openapi.java.utils.ConfigData;
import com.ctrip.openapi.java.utils.SignatureUtils;

// Http������
public class HotelBasicInfoAdapter {

	// hotels
	private static List<City> Cities() {
		List<City> cities = new ArrayList<City>();

		SAXBuilder builder = new SAXBuilder();
		try {
			Document doc = builder.build(new File(
					"D:\\mynew\\RIMS\\src\\国内城市.xml"));
			Element root = doc.getRootElement();

			XPath xpath = XPath.newInstance("/CityDetails/CityDetail");
			List list = xpath.selectNodes(root);

			Iterator iter = list.iterator();
			while (iter.hasNext()) {
				City city = new City();
				Element cityDetail = (Element) iter.next();
				List<Element> cd = cityDetail.getChildren();

				city.setCityCode(cd.get(0).getText());
				city.setCity(cd.get(1).getText());
				city.setCityName(cd.get(2).getText());
				city.setCityEName(cd.get(3).getText());
				city.setCountry(cd.get(4).getText());
				city.setProvince(cd.get(5).getText());
				city.setAirport(cd.get(6).getText());
				// System.out.println(city.getCityCode()+":"+city.getCity()+":"+city.getCityName()+":"+city.getCityEName()+":"+city.getCountry()+":"+city.getProvince()+":"+city.getAirport());
				cities.add(city);
			}

		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// System.out.println(cities.size());
		return cities;
	}

	// ctripinterface --------------
	private static String createHotelRequestXml(String hotelCityCode) {
		StringBuilder sb = new StringBuilder();
		try {
			sb.append("<Request><Header AllianceID=\"");
			sb.append(ConfigData.AllianceId);
			sb.append("\" SID=\"");
			sb.append(ConfigData.SId);
			sb.append("\" TimeStamp=\"");
			long timestamp = SignatureUtils.GetTimeStamp();
			sb.append(timestamp);
			sb.append("\" Signature=\"");

			String signature = SignatureUtils.CalculationSignature(timestamp
					+ "", ConfigData.AllianceId, ConfigData.SecretKey,
					ConfigData.SId, ConfigData.OTA_HotelSearch);
			sb.append(signature);
			sb.append("\" RequestType=\"");
			sb.append(ConfigData.OTA_HotelSearch);
			sb.append("\" AsyncRequest=\"false\" Timeout=\"0\" MessagePriority=\"3\"/><HotelRequest>"
					+ "<RequestBody xmlns:ns=\"http://www.opentravel.org/OTA/2003/05\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">"
					+ "<ns:OTA_HotelSearchRQ Version=\"1.0\" PrimaryLangID=\"zh\" xsi:schemaLocation=\"http://www.opentravel.org/OTA/2003/05 OTA_HotelSearchRQ.xsd\" xmlns=\"http://www.opentravel.org/OTA/2003/05\">"
					+ "<ns:Criteria AvailableOnlyIndicator=\"true\">"
					+ "<ns:Criterion>"
					+ "<ns:HotelRef HotelCityCode=\""
					+ hotelCityCode
					+ "\"/> "
					+ "</ns:Criterion>"
					+ "</ns:Criteria>"
					+ "</ns:OTA_HotelSearchRQ>"
					+ "</RequestBody></HotelRequest></Request>");
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}

		return sb.toString();
	}

	// parseresponse
	private static List<Hotel> findHotels(String hotelCityCode) {
		List<Hotel> hotels = new ArrayList<Hotel>();
		String response = HttpAccessAdapter.getResponseFromCtrip(ConfigData.OTA_HotelSearch,createHotelRequestXml(hotelCityCode));
		// 创建一个新的字符串
		StringReader read = new StringReader(response);
		// 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
		InputSource source = new InputSource(read);

		SAXBuilder builder = new SAXBuilder();
		try {
			Document doc = builder.build(source);
			Element root = doc.getRootElement();
			XPath xpath1 = XPath.newInstance("/Response/Header");
			List list1 = xpath1.selectNodes(root);
			Element item1 = (Element) list1.get(0);
			System.out.println(item1.getAttributeValue("ResultCode"));
			if ("Fail".equals(item1.getAttributeValue("ResultCode"))) {
				System.out.println(item1.getAttributeValue("ResultMsg"));
			}

			XPath xpath = XPath.newInstance("/Response/HotelResponse/*/*/*");
			List list = xpath.selectNodes(root);

			Iterator iter = list.iterator();
			while (iter.hasNext()) {
				Element item = (Element) iter.next();
				if (item.getAttributeValue("HotelName") != null
						&& !"".equals(item.getAttributeValue("HotelName"))) {
					Hotel hotel = new Hotel();

					hotel.setHotelName(item.getAttributeValue("HotelName"));
					hotel.setHotelCityCode(item
							.getAttributeValue("HotelCityCode"));
					hotel.setHotelCode(item.getAttributeValue("HotelCode"));
					hotel.setAreaID(item.getAttributeValue("AreaID"));
					// System.out.println(item.getAttributeValue("HotelName")+item.getAttributeValue("HotelCityCode")+item.getAttributeValue("HotelCode")+item.getAttributeValue("AreaID"));//
					Element vendorMessages = (Element) item.getChildren()
							.get(0);
					Element vendorMessage = (Element) vendorMessages
							.getChildren().get(0);
					Element subSection = (Element) vendorMessage.getChildren()
							.get(0);
					Element paragraph = (Element) subSection.getChildren().get(
							0);
					Element text = (Element) paragraph.getChildren().get(0);
					hotel.setParagraph(text.getText());
					// System.out.println(text.getText());//pic
					Element pos = (Element) item.getChildren().get(1);

					// System.out.println(pos.getAttributeValue("Latitude")+"--------"+pos.getAttributeValue("Longitude"));
					hotel.setLatitude(pos.getAttributeValue("Latitude"));
					hotel.setLongitude(pos.getAttributeValue("Longitude"));

					Element address = (Element) item.getChildren().get(2);
					Element addressLine = (Element) address.getChildren()
							.get(0);// System.out.println(addressLine.getText());
					Element addressCityName = (Element) address.getChildren()
							.get(1);// System.out.println(addressCityName.getText());
					Element addressPostalCode = (Element) address.getChildren()
							.get(2);// System.out.println(addressPostalCode.getText());
					hotel.setAddressLine(addressLine.getText());
					hotel.setCityName(addressCityName.getText());
					hotel.setPostalCode(addressPostalCode.getText());

					Element hotelStarRate = (Element) item.getChildren().get(3);
					// System.out.println(hotelStarRate.getAttributeValue("Rating"));
					Element ctripStarRate = (Element) item.getChildren().get(4);
					// System.out.println(ctripStarRate.getAttributeValue("Rating"));
					Element ctripRecommendRate = (Element) item.getChildren()
							.get(5);
					// System.out.println(ctripRecommendRate.getAttributeValue("Rating"));
					Element ctripCommRate = (Element) item.getChildren().get(6);
					// System.out.println(ctripCommRate.getAttributeValue("Rating"));
					Element commSurroundingRate = (Element) item.getChildren()
							.get(7);
					// System.out.println(commSurroundingRate.getAttributeValue("Rating"));
					Element commFacilityRate = (Element) item.getChildren()
							.get(8);
					// System.out.println(commFacilityRate.getAttributeValue("Rating"));
					Element commCleanRate = (Element) item.getChildren().get(9);
					// System.out.println(commCleanRate.getAttributeValue("Rating"));
					Element commServiceRate = (Element) item.getChildren().get(
							10);
					// System.out.println(commServiceRate.getAttributeValue("Rating"));

					hotel.setHotelStarRate(hotelStarRate
							.getAttributeValue("Rating"));
					hotel.setCtripStarRate(ctripStarRate
							.getAttributeValue("Rating"));
					hotel.setCtripRecommendRate(ctripRecommendRate
							.getAttributeValue("Rating"));
					hotel.setCtripCommRate(ctripCommRate
							.getAttributeValue("Rating"));
					hotel.setCommCleanRate(commCleanRate
							.getAttributeValue("Rating"));
					hotel.setCommFacilityRate(commFacilityRate
							.getAttributeValue("Rating"));
					hotel.setCommServiceRate(commServiceRate
							.getAttributeValue("Rating"));
					hotel.setCommSurroundingRate(commSurroundingRate
							.getAttributeValue("Rating"));

					List<RelativePosition> rp = new ArrayList<RelativePosition>();
					List<Element> relations = (List<Element>) item
							.getChildren();
					for (int i = 11; i < relations.size(); i++) {
						if ("RelativePosition".equals(relations.get(i)
								.getName())) {
							RelativePosition relativePosition = new RelativePosition();
							relativePosition.setHotelCode(hotel.getHotelCode());
							relativePosition.setDestName(relations.get(i)
									.getAttributeValue("Name"));
							relativePosition.setUnitMeasure(relations.get(i)
									.getAttributeValue("UnitOfMeasureCode"));
							relativePosition.setDistance(relations.get(i)
									.getAttributeValue("Distance"));

							rp.add(relativePosition);
						}
					}

					hotel.setRelativePosition(rp);
					// relativePositions.add(relativePosition);
					hotels.add(hotel);
				}
			}

		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return hotels;
	}

	// jdbc save
	private static void sychronizeHotels(String hotelCode) throws SQLException {

		List<Hotel> hList = HotelBasicInfoAdapter.findHotels(hotelCode);
		int temp = 0;
		Connection con = null;
		java.sql.PreparedStatement st = null;
		java.sql.PreparedStatement st1 = null;
		Map<String, String> paraMap = new HashMap<String, String>();
		// Integer id = (Integer)
		// this.getDao().getSqlMapClientTemplate().queryForObject("maxbshz",paraMap);
		// String errorrowarea="none";

		// Date dates=new Date();
		con = DBPool.getConnection();
		if (con != null)
			System.out.println("connection get....................ok");
		st = con.prepareStatement("insert into Hotel ( hotelCode,hotelName,hotelCityCode,"
				+ "areaID, paragraph,latitude,longitude,addressLine,cityName,postalCode,hotelStarRate,ctripRecommendRate,ctripStarRate,"
				+ "ctripCommRate,commSurroundingRate,commFacilityRate,commCleanRate,commServiceRate)"
				+ " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
		st1 = con
				.prepareStatement("insert into RelativePosition ( hotelCode,destName,unitMeasure,distance)"
						+ " values(?,?,?,?)");
		Long beginTime = System.currentTimeMillis();
		con.setAutoCommit(false);

		// String aa="";
		for (int row = 0; row < hList.size(); row++) {
			//System.out.println(hList.get(row).getHotelCode()+":"+hList.get(row).getHotelName());
			st.setString(1, hList.get(row).getHotelCode());
			st.setString(2, hList.get(row).getHotelName());// aa=aa+","+creator;
			st.setString(3, hList.get(row).getHotelCityCode());
			st.setString(4, hList.get(row).getAreaID());
			st.setString(5, hList.get(row).getParagraph());
			st.setString(6, hList.get(row).getLatitude());
			st.setString(7, hList.get(row).getLongitude());
			st.setString(8, hList.get(row).getAddressLine());
			st.setString(9, hList.get(row).getCityName());
			st.setString(10, hList.get(row).getPostalCode());
			st.setString(11, hList.get(row).getHotelStarRate());
			st.setString(12, hList.get(row).getCtripRecommendRate());
			st.setString(13, hList.get(row).getCtripStarRate());
			st.setString(14, hList.get(row).getCtripCommRate());
			st.setString(15, hList.get(row).getCommSurroundingRate());
			st.setString(16, hList.get(row).getCommFacilityRate());
			st.setString(17, hList.get(row).getCommCleanRate());
			st.setString(18, hList.get(row).getCommServiceRate());
			st.addBatch();
			for (int row1 = 0; row1 < hList.get(row).getRelativePosition()
					.size(); row1++) {
				st1.setString(1, hList.get(row).getRelativePosition().get(row1)
						.getHotelCode());
				st1.setString(2, hList.get(row).getRelativePosition().get(row1)
						.getDestName());
				st1.setString(3, hList.get(row).getRelativePosition().get(row1)
						.getUnitMeasure());
				st1.setString(4, hList.get(row).getRelativePosition().get(row1)
						.getDistance());
				st1.addBatch();
			}
			/*
			 * if(row%1000==0){ st.executeBatch();st.clearBatch(); temp=0; }
			 * else { temp=row; }
			 */

		}
		/*
		 * if(temp!=0) {
		 */
		st1.executeBatch();
		st1.clearBatch();
		st.executeBatch();
		st.clearBatch();
		// }
		// System.out.println(aa+","+datestring);
		con.commit();
		Long endTime = System.currentTimeMillis();
		System.out.println("pst+batch：" + (endTime - beginTime) / 1000 + "秒");
		st1.close();
		st.close();
		con.close();

	}

	public static void downloadAllHotelBasicInfo() throws SQLException,
			InterruptedException {
		List<City> cities = HotelBasicInfoAdapter.Cities();

		int count = 0;
		for (int i = 0; i < cities.size(); i++) {
			if (new Integer(cities.get(i).getCity()).intValue() >= 903) {
				System.out.println(cities.get(i).getCityName() + "--"
						+ cities.get(i).getCity());
				HotelBasicInfoAdapter.sychronizeHotels(cities.get(i).getCity());
				// count++;
				// if(count%2==0){
				Thread.sleep(2000);
				// count=0;
				// }
			}
		}
		System.out.println("downloadAllHotelBasicInfo success!!");
	}
  
	public static void main(String[] args) throws SQLException,
			InterruptedException, JDOMException, IOException, ParseException {
		
		HotelBasicInfoAdapter.downloadAllHotelBasicInfo();
	}

}
